package com.tracesystem.util;

import com.aliyun.oss.*;
import com.aliyun.oss.model.GetObjectRequest;
import com.tracesystem.config.OSSproperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

/**
 * @author JMOCOK
 * @description 文件上传下载删除
 * @date 2022/3/25  10:20
 */
@Component
public class OSSTemplate {

    private OSSClientBuilder ossBuilder = new OSSClientBuilder();
    @Autowired
    private OSSproperties ossProperties;

    public String uploadFile(String bucketName, String name, InputStream file){

        OSS ossClient = ossBuilder.build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());

        try {
            ossClient.putObject(bucketName,name,file);

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return name;
    }

    public String uploadFile(String name, InputStream file){
        return uploadFile(ossProperties.getBucketName(),name,file);
    }

    public void removeFile(String bucketName, String name){

        OSS ossClient = ossBuilder.build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());

        try {
            ossClient.deleteObject(bucketName,name);

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

    public void download(String bucketName,String name,String fileName){
        OSS ossClient = ossBuilder.build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        try {
            ossClient.getObject(new GetObjectRequest(bucketName, name), new File("C:\\Users\\Administrator\\Downloads\\"+fileName));
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public void download(String name,String fileName){
        download(ossProperties.getBucketName(),name,fileName);
    }
}
